package com.xcd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xcd.reggie.common.BaseContext;
import com.xcd.reggie.common.R;
import com.xcd.reggie.dto.OrdersDto;
import com.xcd.reggie.entity.Orders;
import com.xcd.reggie.entity.User;
import com.xcd.reggie.service.OrdersService;
import com.xcd.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.Offset;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrdersService orderService;

    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(Integer page, Integer pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentID());
        orderService.page(ordersPage, queryWrapper);
        return R.success(ordersPage);
    }

    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize, String number) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(number != null, Orders::getNumber, number);


        orderService.page(ordersPage, lambdaQueryWrapper);
        //BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> records = ordersPage.getRecords();
        records = records.stream().map((item) -> {
            Long userId = item.getUserId();
            User byId = userService.getById(userId);
            String name = byId.getName();
            item.setUserName(name);
            return item;
        }).collect(Collectors.toList());
        ordersPage.setRecords(records);


        return R.success(ordersPage);
    }

    @PutMapping
    public R<String> put(@RequestBody Orders orders) {
        log.info("orders -- put() {}", orders);
        orderService.updateById(orders);
        return R.success("ok");
    }
}
